import AsyncMessage from '../services/AsyncMessage';
import * as types from '../constants/actionTypes';



function message_init(id){
    var isEmptyObject = function(e) {
        var t;
        for (t in e)
            return !1;
        return !0
    }

    return async (dispatch) =>{
        let message = await AsyncMessage.init(id);

        message = isEmptyObject(message)? []: JSON.parse(message);
        dispatch({type:types.MESSAGE_CHANGE, messages:{id, item:message}});
    }
}

function message_change(id, messages){
    return async (dispatch) =>{
        // var {ticket, userId, reload}=session;

        AsyncMessage.saveMessages(messages, id)
        .then((data)=>{
            dispatch({type:types.MESSAGE_CHANGE, messages:{id, item:messages}});
        });
    };
}

function clear_message(id){
    return async (dispatch) =>{
        await AsyncMessage.clearMessage(id);
        dispatch({type:types.MESSAGE_CHANGE, messages:{id, item:null}});
    }
}

module.exports = {message_change, clear_message, message_init};
